package com.example.idlefish.MyAccount.activity

import android.content.*
import android.os.*
import android.util.Log
import androidx.activity.*
import com.example.idlefish.MyAccount.pojo.*
import com.example.idlefish.PublicModule.*
import com.example.idlefish.databinding.*
import com.example.idlefish.PublicModule.*
import com.example.idlefish.databinding.*
import com.fasterxml.jackson.databind.*
import com.google.gson.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.*
import kotlin.Result

class RegisterActivity  : ComponentActivity() {
    private lateinit var binding: MyaccountLoginRegisterActivityBinding

    // 网络
    private val client = OkHttpClient()
    private val mapper = ObjectMapper()
    private val handler = Handler(Looper.getMainLooper())
    private val mediaType = "application/json;charset=utf-8".toMediaTypeOrNull()
    private val message = Message()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = MyaccountLoginRegisterActivityBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.registerButton.setOnClickListener{
            register()
        }
    }

    /*
    * 测试数据
    * 123@qq.com
    * 123
    *
    * */
    private fun register() {
        // 获得数据
        val newName = binding.newUserName.text.toString()
        val newPassword = binding.newPassword.text.toString()
        val newInfo = User(null, newName, newPassword, null,null, null, 1)
        val intent = Intent()
        intent.putExtra("addInfo", newInfo)
        setResult(RESULT_OK, intent)
        registerPost(newInfo)
        finish()
    }

    /* 注册
    *
    * */
    private fun registerPost(info: User){
        try {
            val request = Request.Builder().url(NetworkSettings.USER + "register?account=${info.account}&password=${info.password}")
                .post(
                mapper.writeValueAsString(info).toRequestBody(mediaType)
            ).build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    message.what = ResponseCode.REQUEST_FAILED
                    handler.post {
                        Utils.showMessage(applicationContext, message)
                    }
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    val gson = Gson()
                    
                    if (response.isSuccessful) {
                        val body = response.body
                        if (body != null) {
                            val responseData = response.body?.string()
                            val jSon = gson.fromJson(responseData, UserResult::class.java)
                            val user = jSon.data
                            val intent = Intent()
                            intent.putExtra("addInfo", user)
                            setResult(RESULT_OK, intent)
                            finish()

                        } else {
                            message.what = ResponseCode.EMPTY_RESPONSE
                        }
                    } else {
                        message.what = ResponseCode.SERVER_ERROR
                    }
                    handler.post {
                        Utils.showMessage(applicationContext, message)
                    }
                }
            })
        } catch (e: Exception) {
            message.what = ResponseCode.JSON_SERIALIZATION
            Log.i("捕获异常", message.toString())
            e.printStackTrace()
        }
    }




}